//
//  MPGridViewCell_iPad.m
//  MissPaparazzi
//
//  Created by Alexey Aleshkov on 19.08.12.
//  Copyright (c) 2012 DzeTech. All rights reserved.
//


#import "MPGridViewCell.h"
#import "UIGlossyButton+MPNavigationBarTitle.h"
#import "MPStore.h"


@interface MPGridViewCell ()
@property (nonatomic, assign) MPGridViewCellState state;
@end


@implementation MPGridViewCell

@synthesize delegate = _delegate;
@synthesize state = _state;
@synthesize data = _data;

#pragma mark -
#pragma mark Init / Dealloc

- (id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	if (!self) {
		return nil;
	}
	return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
	self = [super initWithCoder:aDecoder];
	if (!self) {
		return nil;
	}
	
	_titleLabel = (UILabel *)[self viewWithTag:1];
	
	UIView *contentView = [self viewWithTag:2];
	
	_videoImageView = (UIImageView *)[contentView viewWithTag:21];
	UIImageView *playImageView = (UIImageView *)[contentView viewWithTag:22];
	playImageView.userInteractionEnabled = YES;
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playVideoAction:)];
	[playImageView addGestureRecognizer:gestureRecognizer];
	[gestureRecognizer release];
	
	_buyView = [contentView viewWithTag:23];
	_buyButton = (UIGlossyButton *)[_buyView viewWithTag:231];
	[_buyButton addTarget:self action:@selector(buy:) forControlEvents:UIControlEventTouchUpInside];
	[_buyButton setGrayStyle];
	
	_downloadView = [contentView viewWithTag:24];
	_downloadButton = (UIGlossyButton *)[_downloadView viewWithTag:241];
	[_downloadButton addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
	[_downloadButton setGrayStyle];
	
	_downloadingView = [contentView viewWithTag:25];
	UIView *downloadingContentView = [_downloadingView viewWithTag:251];
	_downloadingProgressLabel = (UILabel *)[downloadingContentView viewWithTag:2511];
	_downloadingProgressView = (UIProgressView *)[downloadingContentView viewWithTag:2512];
	UIGlossyButton *downloadingCancelButton = (UIGlossyButton *)[_downloadingView viewWithTag:252];
	[downloadingCancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
	[downloadingCancelButton setGrayStyle];
	
	_processingView = [contentView viewWithTag:26];
	//UIView *processingContentView = [_processingView viewWithTag:261];
	//UILabel *processingProgressLabel = (UILabel *)[processingContentView viewWithTag:2611];
	UIGlossyButton *processingCancelButton = (UIGlossyButton *)[_processingView viewWithTag:262];
	[processingCancelButton setGrayStyle];
	NSString *cancelString = NSLocalizedString(@"MainView.EpisodesGridView.Item.Cancel", nil);
	[processingCancelButton setTitle:cancelString forState:UIControlStateNormal];
	
	_openView = [contentView viewWithTag:27];
	UIGlossyButton *openOpenButton = (UIGlossyButton *)[_openView viewWithTag:271];
	[openOpenButton addTarget:self action:@selector(open:) forControlEvents:UIControlEventTouchUpInside];
	[openOpenButton setGrayStyle];
	NSString *openString = NSLocalizedString(@"MainView.EpisodesGridView.Item.Open", nil);
	[openOpenButton setTitle:openString forState:UIControlStateNormal];

	_removeButton = (UIGlossyButton *)[_openView viewWithTag:272];
	[_removeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
	[_removeButton setGrayStyle];

	return self;
}

- (void)dealloc
{
	[_data release];
	[super dealloc];
}

#pragma mark -
#pragma mark Overrides

/// prevent all controls from being highlighted
- (void)recursiveEnumerateSubviewsUsingBlock:(void (^)(UIView *view, BOOL *stop))block
{
	return;
}

#pragma mark -
#pragma mark Properties

- (void)updateDataDownloadProgress:(MPEpisode *)data
{
	NSString *readMBsString = [NSString stringWithFormat:@"%.1f", data.readBytes / 1024.0 / 1024.0];
	NSString *totalMBsString = [NSString stringWithFormat:@"%.1f", data.totalBytes / 1024.0 / 1024.0];
	NSString *downloadingFormat = NSLocalizedString(@"MainView.EpisodesGridView.Item.DownloadingFormat", nil);
	NSString *titleString = [NSString stringWithFormat:downloadingFormat, readMBsString, totalMBsString];
	
	_downloadingProgressLabel.text = titleString;
	_downloadingProgressView.progress = ((float)data.readBytes) / ((float)data.totalBytes);
}

- (void)setState:(MPGridViewCellState)state
{
	_state = state;
	
	switch (_state) {
		case MPGridViewCellDownload:
			_buyView.hidden = YES;
			_downloadView.hidden = NO;
			_downloadingView.hidden = YES;
			_processingView.hidden = YES;
			_openView.hidden = YES;
			break;
		case MPGridViewCellDownloading:
			_buyView.hidden = YES;
			_downloadView.hidden = YES;
			_downloadingView.hidden = NO;
			_processingView.hidden = YES;
			_openView.hidden = YES;
			break;
		case MPGridViewCellProcessing:
			_buyView.hidden = YES;
			_downloadView.hidden = YES;
			_downloadingView.hidden = YES;
			_processingView.hidden = NO;
			_openView.hidden = YES;
			break;
		case MPGridViewCellDownloaded:
			_buyView.hidden = YES;
			_downloadView.hidden = YES;
			_downloadingView.hidden = YES;
			_processingView.hidden = YES;
			_openView.hidden = NO;
			break;
			
		default:
			_state = MPGridViewCellBuy;
			_buyView.hidden = NO;
			_downloadView.hidden = YES;
			_downloadingView.hidden = YES;
			_processingView.hidden = YES;
			_openView.hidden = YES;
			break;
	}
}

- (void)updateDataState:(MPEpisode *)data
{
	if (!data.wasPurchased.boolValue && !data.free.boolValue) {
		[self setState:MPGridViewCellBuy];
	} else {
		if (data.downloaded.boolValue) {
			[self setState:MPGridViewCellDownloaded];
		} else {
			switch (data.downloadState) {
				case MPEpisodeDownloadDownloading:
					[self setState:MPGridViewCellDownloading];
					[self updateDataDownloadProgress:data];
					break;
				case MPEpisodeDownloadProcessing:
					[self setState:MPGridViewCellProcessing];
					break;
				case MPEpisodeDownloadDownloaded:
					[self setState:MPGridViewCellDownloaded];
					break;
					
				default:
					[self setState:MPGridViewCellDownload];
					break;
			}
		}
	}
}

- (void)setData:(MPEpisode *)data
{
    id oldValue = _data;
    [oldValue removeObserver:self forKeyPath:@"thumbnailImage"];
    [oldValue removeObserver:self forKeyPath:@"imageDownloaded"];
    [oldValue removeObserver:self forKeyPath:@"readBytes"];
    [oldValue removeObserver:self forKeyPath:@"downloadState"];
    [oldValue removeObserver:self forKeyPath:@"downloaded"];
    [oldValue removeObserver:self forKeyPath:@"wasPurchased"];

    _data = [data retain];
    [_data addObserver:self forKeyPath:@"wasPurchased" options:NSKeyValueObservingOptionNew context:NULL];
    [_data addObserver:self forKeyPath:@"downloaded" options:NSKeyValueObservingOptionNew context:NULL];
    [_data addObserver:self forKeyPath:@"downloadState" options:NSKeyValueObservingOptionNew context:NULL];
    [_data addObserver:self forKeyPath:@"readBytes" options:NSKeyValueObservingOptionNew context:NULL];
    [_data addObserver:self forKeyPath:@"imageDownloaded" options:NSKeyValueObservingOptionNew context:NULL];
    [_data addObserver:self forKeyPath:@"thumbnailImage" options:NSKeyValueObservingOptionNew context:NULL];
    _titleLabel.text = _data.name;
    _videoImageView.image = _data.thumbnailImage;
    
    NSString *buyFormat = NSLocalizedString(@"MainView.EpisodesGridView.Item.BuyFormat", nil);
    NSString *buyString = [NSString stringWithFormat:buyFormat, _data.price];
    [_buyButton setTitle:buyString forState:UIControlStateNormal];

    NSString *downloadFormat = NSLocalizedString(@"MainView.EpisodesGridView.Item.DownloadFormat", nil);
    NSString *downloadString = [NSString stringWithFormat:downloadFormat, _data.size];
    [_downloadButton setTitle:downloadString forState:UIControlStateNormal];
    
    NSString *removeString;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        removeString = NSLocalizedString(@"MainView.EpisodesGridView.Item.Remove", nil);
    } else {
        NSString *removeFormat = NSLocalizedString(@"MainView.EpisodesGridView.Item.RemoveFormat", nil);
        removeString = [NSString stringWithFormat:removeFormat, _data.size];
    }
    [_removeButton setTitle:removeString forState:UIControlStateNormal];
    
    [self updateDataState:_data];
    
    [oldValue release];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
	MPEpisode *data = object;
	
	if ([keyPath isEqualToString:@"wasPurchased"] || [keyPath isEqualToString:@"downloaded"] || [keyPath isEqualToString:@"downloadState"]) {
		[self updateDataState:data];
	} else if ([keyPath isEqualToString:@"readBytes"]) {
		[self updateDataDownloadProgress:data];
		//NSLog(@"downloading");
	} else if ([keyPath isEqualToString:@"imageDownloaded"] || [keyPath isEqualToString:@"thumbnailImage"]) {
		_videoImageView.image = _data.thumbnailImage;
	}
}

#pragma mark -
#pragma mark Actions

- (void)playVideoAction:(id)sender
{
	switch (_state) {
		case MPGridViewCellBuy:
			[self buy:self];
			break;
		case MPGridViewCellDownloaded:
			[self open:self];
			break;
			
		default:
			break;
	}
}

- (void)buy:(id)sender
{
	SEL sel = @selector(MPGridViewCell:buy:);
	if ([_delegate respondsToSelector:sel]) {
		[_delegate performSelector:sel withObject:self withObject:_data];
	}
}

- (void)open:(id)sender
{
	SEL sel = @selector(MPGridViewCell:open:);
	if ([_delegate respondsToSelector:sel]) {
		[_delegate performSelector:sel withObject:self withObject:_data];
	}
}

- (void)download:(id)sender
{
	SEL sel = @selector(MPGridViewCell:download:);
	if ([_delegate respondsToSelector:sel]) {
		[_delegate performSelector:sel withObject:self withObject:_data];
	}
}

- (void)cancel:(id)sender
{
	SEL sel = @selector(MPGridViewCell:cancelDownloading:);
	if ([_delegate respondsToSelector:sel]) {
		[_delegate performSelector:sel withObject:self withObject:_data];
	}
}

- (void)remove:(id)sender
{
	SEL sel = @selector(MPGridViewCell:remove:);
	if ([_delegate respondsToSelector:sel]) {
		[_delegate performSelector:sel withObject:self withObject:_data];
	}
}

@end
